package com.jizhi.onework.controller;

import com.jizhi.onework.controller.common.BaseController;
import com.jizhi.onework.dataobj.param.UserParam;
import com.jizhi.onework.dataobj.vo.UserVO;
import com.jizhi.onework.framework.model.jwt.CustomizedToken;
import com.jizhi.onework.framework.context.OperationContextHolder;
import com.jizhi.onework.framework.model.Result;
import com.jizhi.onework.framework.model.ServiceResponse;
import com.jizhi.onework.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 主门面接口
 *
 * @author hzhang7
 */
@RestController
public class MainController extends BaseController {

    @Autowired
    private UserService userService;

    @RequestMapping("/api/register")
    public Result<UserVO> register(@RequestBody UserParam userParam) {
        // 插入用户
        ServiceResponse<UserVO> response = userService.registerUser(userParam.toDTO());
        if (!response.isSuccess()) {
            return new Result<>(false, null, response.getError());
        }

        return convertResponseToResult(response);
    }

    @RequestMapping("/api/login")
    public Result login(@RequestBody UserParam userParam) {

        String error = null;
        CustomizedToken token = new CustomizedToken(userParam.getUserName(), userParam.getPassword(), "UserRealm");
        try {
            SecurityUtils.getSubject().login(token);
        } catch (AuthenticationException e) {
            error = e.getMessage();
        }

        if (StringUtils.isNotBlank(error)) {
            return new Result(false, null, error);
        }

        return new Result(true, OperationContextHolder.get(), null);

    }

    @RequestMapping("/main")
    public String index(HttpServletRequest request, HttpServletResponse response) {
        response.setHeader("root", request.getContextPath());
        return "登陆成功!";
    }

    @RequestMapping("/toLogin")
    public String toLogin(HttpServletRequest request, HttpServletResponse response) {
        response.setHeader("root", request.getContextPath());
        return "请登录";
    }

    @RequestMapping("/logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        if (subject != null) {
            subject.logout();
        }
        return "退出登录!";
    }

    @RequestMapping("/error/unAuth")
    public String unAuth() {
        return "无权限";
    }
}
